﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Memcached.ClientLibrary;
using System.Collections;

namespace Phoenix.Cache
{
    /// <summary>
    /// Memcached缓存提供程序
    /// </summary>
    public class MemcachedProvider : ICacheProvider
    {
        #region Fields

        /// <summary>
        /// Memcached客户端
        /// </summary>
        private MemcachedClient client;

        #endregion

        #region Constructors

        /// <param name="client">Memcached客户端</param>
        internal MemcachedProvider(MemcachedClient client)
        {
            this.client = client;
        }
        
        #endregion

        #region ICacheProvider Members

        public bool Contains(string key)
        {
            VerifyKey(key);

            return client.KeyExists(key);
        }

        public object Get(string key)
        {
            VerifyKey(key);

            return client.Get(key);
        }

        public IDictionary Gets(string[] keys)
        {
            if (keys == null)
            {
                throw new ArgumentNullException("keys", "名称集合不能为空");
            }

            foreach (string key in keys)
            {
                VerifyKey(key);
            }

            return client.GetMultiple(keys);
        }

        public void Add(string key, object value)
        {
            VerifyKey(key);

            client.Set(key, value); 
        }

		//public void Add(string key, object value,int hashCode)
		//{
		//    VerifyKey(key);

		//    client.Set(key, value,hashCode);
		//}

		public void Add(string key, object value, DateTime expr)
		{
			VerifyKey(key);

			client.Set(key, value, expr);
		}

		//public void Add(string key, object value, DateTime expr, int hashCode)
		//{
		//    VerifyKey(key);

		//    client.Set(key, value, expr, hashCode);
		//}

        public void Remove(string key)
        {
            VerifyKey(key);

            client.Delete(key);
        }

        public void Clear()
        {
            client.FlushAll();
        }

        #endregion

        #region Helper Functions

        private static void VerifyKey(string key)
        {
            if (string.IsNullOrEmpty(key))
            {
                throw new ArgumentException("缓存的名称不能为空");
            }
        }

        #endregion
	}
}
